from datetime import datetime
import json
import time

from django.http import HttpResponse
from django.conf import settings

from user.models import Record


class LoadDatetime(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)


def render_json(data, code=0):
    result = {
        'code': code,
        'data': data
    }
    if settings.DEBUG:
        json_str = json.dumps(result, indent=4, ensure_ascii=False, sort_keys=False, cls=LoadDatetime)
    # json_str = json.dumps(result, ensure_ascii=False, separators=[',', ':'])
    else:
        json_str = json.dumps(result, ensure_ascii=False, separators=[',', ':'], cls=LoadDatetime)
    return HttpResponse(json_str)


# func excute times
def print_func_runtime(func):
    def count_time(*args, **kwargs):
        start_time = time.time()
        res = func(*args, **kwargs)
        end_time = time.time()
        print("This function run times is:{:.3f}s".format(end_time - start_time))
        return res

    return count_time


def handle_record_operate(method):
    def wrapper(func):
        def sub_wrapper(*args, **kwargs):
            try:
                res = func(*args, **kwargs)
                # print("record wrapper:", args[0].META)
                request_url = args[0].META.get('PATH_INFO')
                request_host = args[0].META.get('REMOTE_ADDR')
                record_obj = {
                    'user_id': args[0].user.id,
                    'request_url': request_url,
                    'request_type': method,
                    'request_host': request_host,
                    'login_at': args[0].user.update_at
                }
                Record.objects.create(**record_obj)
                return res
            except Exception as e:
                print('-----Create Record error: %s' % e)
                return res
        return sub_wrapper
    return wrapper
